class MyDrivingRender {
  constructor(AMap, initOpts) {
    this["CLASS_NAME"] = "AMap.MyDrivingRender";
    let markerOffset = [-12, -30];
    let forOf = function forOf(arr, cb) {
      for (let i = 0, len = arr.length; i < len; i++) {
        cb(arr[i])
      }
    };
    var me = this;
    initOpts = initOpts || {};
    me._styleOpts = {};
    me._styleOpts["zIndex"] = typeof initOpts["zIndex"] === "number" ? initOpts["zIndex"] : 50;
    me._showTraffic = initOpts["showTraffic"];
    me._eventSelf = initOpts["eventSelf"];
    me.showDir = initOpts["showDir"];
    me._currentRouteTitle = null;
    me._currentRouteOptenitem = null;
    me.storeInfo = initOpts["storeInfo"];
    me.autoRender = function (options, drivingObject) {
      me.clear(1);
      if (!options || !options.data || !options.panel && !options.map) {
        return
      }
      this.options = options;
      this.hideMarkers = options["hideMarkers"] || false;
      if (options.map) {
        this._infoWindow = new AMap.InfoWindow({
          size: new AMap.Size(0, 0),
          isCustom: true,
          offset: new AMap.Pixel(0, -30)
        });
        this._overlays = [];
        this._route = [];
        this._highlightOverlay = null;
        if (!options.panel) {
          this.drawRouteOverlays(0)
        }
      }
      if (options.panel) {
        if (Object.prototype.toString.call(options.panel) === "[object String]") {
          options.panel = document.getElementById(options.panel)
        }
        options.panel.appendChild(this.view.createPanel(options.data));
        this.enableListeners()
      }
    };
    me.clear = function (reserve) {
      this.clearPanel();
      this.clearOverlays(reserve)
    };
    me.drawRoute = function (index) {
      var data = this.options.data
        , route = data.routes[index];
      var distance = route.distance
        , steps = route.steps;
      var walkPaths = []
        , drivingPaths = [];
      walkPaths.push([data.start.location, steps[0].path[0]]);
      var lastStepPath = steps[steps.length - 1].path;
      walkPaths.push([lastStepPath[lastStepPath.length - 1], data.end.location]);
      for (var i = 0, step; i < steps.length; i++) {
        step = steps[i];
        drivingPaths = drivingPaths.concat(step.path)
      }
      if (drivingPaths.length > 0) {
        drivingPaths = [drivingPaths]
      }
      drivingPaths.steps = steps;
      this.clearRoute();
      this._route = this.addOverlays([], walkPaths, drivingPaths, {
        strokeOpacity: .4
      })
    };
    me.clearRoute = function () {
      if (this._route) {
        for (var i = 0; i < this._route.length; i++) {
          this._route[i].setMap(null)
        }
        this._route = []
      }
    };
    me.drawRouteOverlays = function (index) {
      var data = this.options.data
        , route = data.routes[index];
      var distance = route.distance
        , steps = route.steps;
      var walkPaths = []
        , drivingPaths = []
        , points = [];
      points.push(data.start);
      if (data.waypoints) {
        var waypoints = data.waypoints;
        for (var i = 0, len = waypoints.length; i < len; i++) {
          points.push(waypoints[i])
        }
      }
      points.push(data.end);
      walkPaths.push([data.start.location, steps[0].path[0]]);
      var lastStepPath = steps[steps.length - 1].path;
      walkPaths.push([lastStepPath[lastStepPath.length - 1], data.end.location]);
      for (var _i = 0, step; _i < steps.length; _i++) {
        step = steps[_i];
        drivingPaths = drivingPaths.concat(step.path)
      }
      if (drivingPaths.length > 0) {
        drivingPaths = [drivingPaths]
      }
      drivingPaths.steps = steps;
      this.clearOverlays(1);
      points.forEach((point) => {
        let temp = this.storeInfo.filter(store=>store.key.equals(point.location));
        if (temp.length === 1){
          point.storeName = temp[0].storeName;
          point.address = temp[0].address;
          point.contacts = temp[0].contacts;
          point.tel = temp[0].tel;
        }else{
          point.storeName = "此未匹配到店铺";
          point.address = point.location.toJSON();
          point.contacts = "";
          point.tel = '';
        }
      });

      this._overlays = this.addOverlays(points, walkPaths, drivingPaths);
      if (me.options["autoFitView"]) {
        me.options.map.setFitView(this._overlays)
      }
    };
    me.addOverlays = function (points, walkPaths, drivingPaths, styleOptions) {
      var _this = this;
      var map = this.options.map;
      styleOptions = styleOptions || {
        strokeOpacity: 1
      };
      var _overlays = [];
      if (!this.hideMarkers) {
        if (points[0]) {
          if (!this.startMarker) {
            this.startMarker = new AMap.Marker({
              offset: markerOffset,
              map: map,
              content: '<div class="amap-lib-marker-from"></div>',
              innerOverlay: true
            });
            this.startMarker.isOfficial = true
          }
          var start = this.startMarker;
          start.setPosition(points[0].location);
          start.setMap(map);
          start._data = points[0];
          start.on("click", this.listener.markerClick);
          AMap.Event.addListener(start, "click", this.listener.markerClick);
          _overlays.push(start)
        }
        if (points.length > 1) {
          if (!this.endMarker) {
            this.endMarker = new AMap.Marker({
              offset: markerOffset,
              map: map,
              content: '<div class="amap-lib-marker-to"></div>',
              innerOverlay: true
            });
            this.endMarker.isOfficial = true
          }
          var end = this.endMarker;
          end.setPosition(points[points.length - 1].location);
          end.setMap(map);
          end._data = points[points.length - 1];
          end.on("click", this.listener.markerClick);
          AMap.Event.addListener(end, "click", this.listener.markerClick);
          _overlays.push(end)
        }
        for (var i = 1, point; i < points.length - 1; i++) {
          if (points[i].isWaypoint) {
            point = new AMap.Marker({
              map: map,
              offset: markerOffset,
              position: points[i].location,
              content: '<div class="amap-lib-marker-mid"></div>',
              innerOverlay: true
            });
            point._data = points[i];
            AMap.Event.addListener(point, "click", this.listener.markerClick)
          }
          point.isOfficial = true;
          _overlays.push(point)
        }
      }
      styleOptions = me.util.extend({}, me._styleOpts, styleOptions);
      for (var _i2 = 0, drivingPath; _i2 < drivingPaths.length; _i2++) {
        var trafficGradient = undefined;
        if (me._showTraffic && drivingPaths.steps) {
          (function () {
              var trafficGradientValues = [];
              var totalDistance = 0;
              forOf(drivingPaths.steps, function (step) {
                if (step.tmcsPaths) {
                  forOf(step.tmcsPaths, function (tmcsPath) {
                    totalDistance += tmcsPath.distance
                  })
                } else {
                  totalDistance += 100
                }
              });
              var currentDistance = 0;
              forOf(drivingPaths.steps, function (step) {
                if (step.tmcsPaths) {
                  forOf(step.tmcsPaths, function (tmcsPath) {
                    currentDistance += tmcsPath.distance;
                    trafficGradientValues.push([currentDistance / totalDistance, _this.getColorByTmcsStatus(tmcsPath.status)])
                  })
                } else {
                  currentDistance += 100;
                  trafficGradientValues.push([currentDistance / totalDistance, _this.getColorByTmcsStatus("")])
                }
              });
              trafficGradient = {
                values: trafficGradientValues
              }
            }
          )()
        }
        drivingPath = new AMap.Polyline(me.util.extend({}, styleOptions, {
          map: map,
          path: drivingPaths[_i2],
          lineJoin: "round",
          strokeColor: "#0091ff",
          isOutline: me.options["isOutline"],
          outlineColor: me.options["outlineColor"],
          borderWeight: 2,
          lineGradient: trafficGradient,
          strokeOpacity: 1,
          showDir: me.showDir,
          strokeWeight: 6,
          innerOverlay: true
        }));
        drivingPath.isOfficial = true;
        _overlays.push(drivingPath);
        me._drivingPolyline = drivingPath
      }
      for (var _i3 = 0, walkPath; _i3 < walkPaths.length; _i3++) {
        walkPath = new AMap.Polyline(me.util.extend({}, styleOptions, {
          map: map,
          path: walkPaths[_i3],
          strokeColor: "grey",
          strokeStyle: "dashed",
          strokeWeight: 6,
          lineJoin: "bevel",
          innerOverlay: true
        }));
        walkPath.isOfficial = true;
        _overlays.push(walkPath)
      }
      if (me.showDir) ;
      return _overlays
    };
    me.getColorByTmcsStatus = function (status) {
      var color;
      switch (status) {
        case "畅通":
          color = "#1BAC2E";
          break;
        case "缓行":
          color = "#FFA700";
          break;
        case "拥堵":
          color = "#E94B37";
          break;
        case "严重拥堵":
          color = "#A81212";
          break;
        default:
          color = "#adadad";
          break
      }
      return color
    };
    me.clearPanel = function () {
      if (this.options && this.options.panel) {
        var a = me.util.getElementsByClassName("amap-call", "div", this.options.panel)[0];
        if (a) {
          a.removeEventListener("click", me.listener.gotoAMap)
        }
        this.options.panel.innerHTML = ""
      }
    };
    me.clearOverlays = function (reserve) {
      if (!reserve) {
        if (this.startMarker) {
          this.startMarker.setMap();
          this.startMarker = null
        }
        if (this.endMarker) {
          this.endMarker.setMap();
          this.endMarker = null
        }
      }
      if (this._overlays) {
        for (var i = 0, overlay; i < this._overlays.length; i++) {
          overlay = this._overlays[i];
          overlay.setMap(null)
        }
        this._overlays = []
      }
      if (this._infoWindow) {
        this._infoWindow.close()
      }
      if (this._highlightOverlay) {
        this._highlightOverlay.setMap(null);
        this._highlightOverlay = null
      }
      this.clearRoute()
    };
    me.getTitle = function (route) {
      var policy = route.policy ? " | <span class='blue'>" + route.policy + "</span>" : "";
      var result = me.util.getTime(route.time) + "(" + me.util.getDistance(route.distance) + ")" + policy;
      return result
    };
    me.util = {};
    me.util.extend = function (dest) {
      var sources = Array.prototype.slice.call(arguments, 1), i, j, len, src;
      for (j = 0,
             len = sources.length; j < len; j = j + 1) {
        src = sources[j] || {};
        for (i in src) {
          if (Object.prototype.hasOwnProperty.call(src, i)) {
            if (typeof src[i] === "function" && typeof dest[i] === "function") {
              src[i].__super = dest[i]
            }
            dest[i] = src[i]
          }
        }
      }
      return dest
    };
    me.util.getDistance = function (len) {
      if (len <= 1e3) {
        var s = len;
        return s + "米"
      } else {
        var _s = Math.round(len / 10);
        return "" + _s / 100 + "公里"
      }
    };
    me.util.getTime = function (second) {
      var minute = +(second / 60).toFixed(0);
      if (minute < 60) {
        return "" + minute + "分钟"
      } else {
        return "" + Math.floor(minute / 60) + "小时" + minute % 60 + "分钟"
      }
    };
    me.util.domstr2dom = function (arg) {
      var objE = document.createElement("div");
      objE.innerHTML = arg;
      return objE
    };
    me.util.getElementsByClassName = function (className, tag, parent) {
      var testClass = new RegExp("(^|\\s)" + className + "(\\s|$)");
      tag = tag || "*";
      parent = parent || document;
      var elements = parent.getElementsByTagName(tag);
      var returnElements = [];
      for (var i = 0, current; i < elements.length; i++) {
        current = elements[i];
        if (testClass.test(current.className)) {
          returnElements.push(current)
        }
      }
      return returnElements
    };
    me.enableListeners = function () {
      var unfocusTitles = me.util.getElementsByClassName("planTitle", "div", me.options.panel);
      for (var i = 0, unfocusTitle; i < unfocusTitles.length; i++) {
        unfocusTitle = unfocusTitles[i];
        AMap.Event.addDomListener(unfocusTitle, "click", this.listener.unfocusTitleClick);
        AMap.Event.addDomListener(unfocusTitle, "mouseenter", this.listener.unfocusTitleMouseenter);
        AMap.Event.addDomListener(unfocusTitle, "mouseleave", this.listener.unfocusTitleMouseleave)
      }
      var c_divs = this.util.getElementsByClassName("*", "dt", me.options.panel);
      for (var _i4 = 0, c_div; _i4 < c_divs.length; _i4++) {
        c_div = c_divs[_i4];
        AMap.Event.addDomListener(c_div, "click", this.listener.routeStepItem)
      }
      if (unfocusTitles.length > 0) {
        me.listener.unfocusTitleClick.call(unfocusTitles[0])
      }
    };
    me.listener = {};
    me.listener.markerClick = function () {
      var data = this._data;
      if (data.type === "start" || data.type === "end") {
        me._infoWindow.setOffset(new AMap.Pixel(0, -30))
      } else {
        me._infoWindow.setOffset(new AMap.Pixel(0, 0))
      }
      if (data.name === "起点1" || data.name === "终点1" || data.name === "途经点1")
        ;
      else {
        me._infoWindow.setContent(me.view.createInfowindowContent(data));
        me._infoWindow.open(me.options.map, this.getPosition())
      }
      // me._infoWindow.setContent(me.view.createInfowindowContent(data));
      // me._infoWindow.open(me.options.map, this.getPosition());
      me.options.map.setCenter(this.getPosition())

    };
    me.listener.routeStepItem = function () {
      if (!me.options.map) {
        var _p = this.parentNode;
        var _children = _p.children;
        var _stepIndex;
        for (var i = 0, child; i < _children.length; i++) {
          child = _children[i];
          if (child === this) {
            _stepIndex = i;
            break
          }
        }
        me._eventSelf.emit("panelClick", {
          stepIndex: _stepIndex
        });
        return
      }
      if (me._highlightOverlay) {
        me._highlightOverlay.setMap(null)
      }
      this.style.backgroundColor = "rgb(240, 240, 240)";
      if (me.listener.routeStepItem.last) {
        me.listener.routeStepItem.last.style.backgroundColor = ""
      }
      me.listener.routeStepItem.last = this;
      var p = this.parentNode;
      var children = p.children;
      var stepIndex;
      for (var _i5 = 0, _child; _i5 < children.length; _i5++) {
        _child = children[_i5];
        if (_child === this) {
          stepIndex = _i5;
          break
        }
      }
      if (stepIndex === 0) {
        me.listener.markerClick.call({
          _data: me.options.data.start,
          getPosition: function getPosition() {
            return me.options.data.start.location
          }
        });
        return
      }
      if (stepIndex === children.length - 1) {
        me.listener.markerClick.call({
          _data: me.options.data.end,
          getPosition: function getPosition() {
            return me.options.data.end.location
          }
        });
        return
      }
      me._infoWindow.close();
      stepIndex = stepIndex - 1;
      var step = me.options.data.routes[me._currentRouteIndex].steps[stepIndex];
      var highlight;
      highlight = new AMap.Polyline({
        map: me.options.map,
        path: step.path,
        strokeColor: "red",
        strokeOpacity: .8,
        strokeWeight: 8,
        lineJoin: "round",
        draggable: true,
        innerOverlay: true
      });
      highlight.isOfficial = true;
      me._highlightOverlay = highlight;
      me.options.map.setBounds(highlight.getBounds())
    };
    me.listener.driveTitleClick = function () {
      me._currentRouteTitle.style.display = "block";
      me._currentRouteOptenitem.style.display = "none";
      me.clearOverlays()
    };
    me.listener.unfocusTitleClick = function () {
      var target = arguments[0] && (arguments[0].target || arguments[0].srcElement);
      if (target && target.tagName === "A") {
        return
      }
      if (me._currentRouteTitleStatus === "open" && me._currentRouteTitle === this) {
        me.view.closeCurrentPlanDiv();
        me.clearOverlays()
      } else if (me._currentRouteTitleStatus === "open") {
        me.view.closeCurrentPlanDiv();
        me.view.openPlanDiv(this)
      } else {
        me.view.openPlanDiv(this)
      }
    };
    me.listener.unfocusTitleMouseenter = function (e) {
      var index = this.getAttribute("index");
      me.drawRoute(index);
      me.listener.unfocusTitleMouseenter.last = this
    };
    me.listener.unfocusTitleMouseleave = function (e) {
      me.clearRoute()
    };
    me.view = {};
    me.view.openPlanDiv = function (planDiv) {
      me._currentRouteTitle = planDiv;
      me._currentRouteOptenitem = planDiv.nextSibling;
      me.util.getElementsByClassName("icon-arrow-up", "div", me._currentRouteTitle)[0].className = "icon-arrow-up expand";
      if (me.util.getElementsByClassName("clearfix", "ul", me._currentRouteTitle)[0]) {
        me.util.getElementsByClassName("clearfix", "ul", me._currentRouteTitle)[0].style.display = "inline-block"
      }
      me._currentRouteOptenitem.style.display = "block";
      me._currentRouteTitleStatus = "open";
      var index = me._currentRouteTitle.getAttribute("index");
      me._currentRouteIndex = index;
      if (me.options.map) {
        me.drawRouteOverlays(me._currentRouteIndex)
      }
    };
    me.view.closeCurrentPlanDiv = function () {
      var title = me.util.getElementsByClassName("icon-arrow-up expand", "div", me._currentRouteTitle)[0];
      var fix = me.util.getElementsByClassName("clearfix", "ul", me._currentRouteTitle)[0];
      if (title) {
        title.className = "icon-arrow-up"
      }
      if (fix) {
        fix.style.display = "none"
      }
      me._currentRouteOptenitem.style.display = "none";
      me._currentRouteTitleStatus = "close"
    };
    me.view.createInfowindowContent = function (data) {
      var c = [data.name];
      return c.join("")
    };
    me.view.createInfowindowContent = function (data) {
      var content = document.createElement("div");
      var div = document.createElement("div");
      div.className = "amap-content-body";
      var c = [];
      c.push('<div class="amap-lib-infowindow">');
      c.push('<div class="amap-lib-infowindow-content">');
      c.push('<div class="amap-lib-infowindow-content-wrap">');
      c.push("<div>店铺：" + data.storeName + "</div>");
      c.push("<div>地址：" + data.address + "</div>");
      c.push("<div>联系人：" + data.contacts + "</div>");
      c.push("<div>电话：" + data.tel + "</div>");
      c.push("</div>");
      c.push("</div>");
      c.push("</div>");
      div.innerHTML = c.join("");
      var sharp = document.createElement("div");
      sharp.className = "amap-combo-sharp";
      div.appendChild(sharp);
      var close = document.createElement("div");
      close.className = "amap-combo-close";
      div.appendChild(close);
      close.href = "javascript: void(0)";
      AMap.Event.addDomListener(close, "touchend", function (e) {
        me._infoWindow["close"]()
      });
      AMap.Event.addDomListener(close, "click", function (e) {
        me._infoWindow["close"]()
      });
      content.appendChild(div);
      content.appendChild(close);
      content.appendChild(sharp);
      return content
    };
    me.view.createPanel = function (data) {
      var div = document.createElement("div");
      div.className = "amap-lib-driving";
      if (!data.routes) {
        div.innerHTML = "抱歉，没有合适的路线。";
        return div
      }
      var result = [];
      for (var i = 0, route; i < data.routes.length; i++) {
        route = data.routes[i];
        var isDisplay = false
          , title = me.getTitle(route);
        result = result.concat(me.view.createTitleDiv(i, title, route, !isDisplay));
        result = result.concat(me.view.createOpenitemDiv(i, title, data, isDisplay))
      }
      div.innerHTML = result.join("");
      return div
    };
    me.view.createTitleDiv = function (index, title, route, isDisplay) {
      var steps = route.steps
        , roadNameArray = []
        , roadNames = ""
        , roadNames2 = "";
      var temp = "";
      for (var i = 0, road; i < steps.length; i++) {
        road = steps[i].road;
        if (road && road !== temp) {
          roadNameArray.push(road);
          temp = road
        }
      }
      roadNames = roadNameArray.join(">");
      if (roadNameArray.length > 4) {
        roadNameArray.splice(2, roadNameArray.length - 4, "......");
        roadNames2 = roadNameArray.join(">")
      } else {
        roadNames2 = roadNames
      }
      var r = [];
      r.push('<div class="planTitle" index="' + index + '">');
      r.push("    <h3  class='planTitle_route' title=\"" + roadNames + '">');
      r.push("         <b>" + roadNames2 + "</b>");
      r.push("    </h3>");
      r.push("    <p>" + title + "</p>");
      var d = me.options.data;
      r.push('    <div class="sidebar">');
      r.push('        <div class="icon-arrow-up" href="javascript:void(0)"></div>');
      r.push("    </div>                ");
      r.push("</div>");
      return r
    };
    me.view.createOpenitemDiv = function (index, title, data, isDisplay) {
      var route = data.routes[index]
        , steps = route.steps;
      var r = [];
      r.push('<dl class="plan plan-nobus">');
      r.push("    <dt class=\"start\"><div class='beforedt'></div><div class='afterdt'></div><b>" + data.start.name + "</b></dt>");
      for (var i = 0, step; i < steps.length; i++) {
        step = steps[i];
        r.push(' <dt class="route turn-' + me.getSigns(step.action) + '"  index="' + index + '">                ');
        r.push("  <div class='beforedt'></div><div class='afterdt'></div>       " + step.instruction);
        r.push(" </dt>")
      }
      r.push("    <dt class=\"end\"><div class='beforedt'></div><b>" + data.end.name + "</b></dt>");
      r.push("</dl>");
      return r
    };
    me.getSigns = function (action) {
      var signs = "";
      var routeSign = {
        "左转": "left",
        "右转": "right",
        "靠左": "keepleft",
        "靠右": "keepright",
        "向左前方行驶": "leftup",
        "向左后方行驶": "leftdown",
        "向右前方行驶": "rightup",
        "向右后方行驶": "rightdown",
        "左转调头": "leftback",
        "右转调头": "rightback",
        "进入环岛": "enterRing",
        "离开环岛": "leaveRing",
        "减速行驶": "slow",
        "向左前方行走": "leftup",
        "向左后方行走": "leftdown",
        "向右前方行走": "rightup",
        "向右后方行走": "rightdown",
        "通过人行横道": "crosswalk",
        "通过过街天桥": "overpass",
        "通过地下通道": "underpass",
        "通过广场": "squarepass"
      };
      signs = routeSign[action];
      if (!signs) {
        signs = "advance"
      }
      return signs
    };
  }
}

export default MyDrivingRender;

